package com.hp.easyBuy.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hp.easyBuy.contants.RedixKey;
import com.hp.easyBuy.entity.TAddress;
import com.hp.easyBuy.service.AddressService;
import com.hp.easyBuy.utils.R;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("address")
public class AddressController {
    @Resource
    private AddressService addressService;
    @Resource
    private RedisTemplate redisTemplate;
    //购物车查询地址列表
    //查询所有用户地址数据集合
    @RequestMapping("/getAddressList")
    public R getAddressList(@RequestParam Long userId) {
        List<TAddress> addressList = addressService.getAddressList(userId);
        return R.success(addressList);
    }

    //根据用户id获取地址列表,将默认地址排到第一行
    @RequestMapping("doList")
    public R<List<TAddress>>doList(Integer userid){
        Object obj = redisTemplate.opsForValue().get(RedixKey.ADDRESS_LIST);
        List<TAddress> list=null;
        if(obj==null){
            list= addressService.list(userid);
            redisTemplate.opsForValue().set(RedixKey.ADDRESS_LIST+userid,list);
        }else {
            list = (List<TAddress>) obj;
        }
        return R.success(list);
    }
    //删除地址
    @RequestMapping("doDel")
    public R doDel(Integer addressId){
        boolean result = addressService.removeById(addressId);
        if(result){
            return R.success();
        }else {
            return R.error();
        }
    }
    //设置为默认地址
    @RequestMapping("updateStatus")
    public R uodateStatus(Integer addressId){
        boolean a = addressService.getAddress();
        boolean b = addressService.updateStatus(addressId);
        if(a && b){
            return R.success();
        }else {
            return R.error();
        }
    }
    //修改地址信息
    @RequestMapping("doUpdate")
    public R updateAddress(@RequestBody TAddress address){
        boolean b = addressService.updateById(address);
        if(b){
            return R.success();
        }else {
            return R.error();
        }
    }

    //添加地址
    @RequestMapping("doAdd")
    public R addAddress(@RequestBody TAddress address){
        boolean save = addressService.save(address);
        if(save){
            return R.success();
        }else {
            return R.error();
        }
    }
    //根据地址id获得地址
    @GetMapping("select")
    public R getAddress(Integer addressid){
        TAddress address = addressService.getById(addressid);
        return R.success(address);
    }


}
